﻿var date = new Date(1482595200 * 1000);
console.log(date);
console.log(date.getHours());

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt))
  fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

function Map() {
  /** 存放键的数组(遍历用到) */
  this.keys = new Array();
  /** 存放数据 */
  this.data = new Object();

  /**
   * 放入一个键值对
   * @param {String} key
   * @param {Object} value
   */
  this.put = function(key, value) {
    if (this.data[key] == null) {
      this.keys.push(key);
    }
    this.data[key] = value;
  };

  /**
   * 获取某键对应的值
   * @param {String} key
   * @return {Object} value
   */
  this.get = function(key) {
    return this.data[key];
  };

  /**
   * 删除一个键值对
   * @param {String} key
   */
  this.remove = function(key) {
    this.keys.remove(key);
    this.data[key] = null;
  };

  /**
   * 遍历Map,执行处理函数
   * 
   * @param {Function} 回调函数 function(key,value,index){..}
   */
  this.each = function(fn) {
    if (typeof fn != 'function') {
      return;
    }
    var len = this.keys.length;
    for (var i = 0; i < len; i++) {
      var k = this.keys[i];
      fn(k, this.data[k], i);
    }
  };

  /**
   * 获取键值数组(类似Java的entrySet())
   * @return 键值对象{key,value}的数组
   */
  this.entrys = function() {
    var len = this.keys.length;
    var entrys = new Array(len);
    for (var i = 0; i < len; i++) {
      entrys[i] = {
        key: this.keys[i],
        value: this.data[i]
      };
    }
    return entrys;
  };

  /**
   * 判断Map是否为空
   */
  this.isEmpty = function() {
    return this.keys.length == 0;
  };

  /**
   * 获取键值对数量
   */
  this.size = function() {
    return this.keys.length;
  };

  /**
   * 重写toString 
   */
  this.toString = function() {
    var s = "{";
    for (var i = 0; i < this.keys.length; i++, s += ',') {
      var k = this.keys[i];
      s += k + "=" + this.data[k];
    }
    s += "}";
    return s;
  };
}

app.scopArray = [];
app.mainScope = null;
app.controller('DatepickerDemoCtrl', ['$scope', '$http', function($scope, $http) {

  function getDateStr(dd) {
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期 
    var d = dd.getDate();
    return y + "/" + m + "/" + d;
  }
  $scope.eopen = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    $scope.eopened = true;
  };

  var dd = new Date();
  dd.setDate(dd.getDate() - 1); //获取AddDayCount天后的日期 

  $scope.maxDate = dd;
  $scope.format = "yyyy/MM/dd";

  $scope.date = getDateStr(dd);
  $scope.selectedName = null;
  $scope.names = ["punch"];

  $scope.loadData = function() {
    for (var i = 0; i < app.scopArray.length; i++) {
      app.scopArray[i].init($scope.selectedName, $('#date').val() == null ? "2016/12/25" : $('#date').val());
    }
  }
  //$scope.loadData();
  
  $scope.onComplete = function(scope) {
	  scope.init($scope.selectedName, $('#date').val() == null ? "2016/12/25" : $('#date').val());
  }
  app.mainScope = $scope;

  // var req = {
  //   method: 'GET',

  //   url: '/statistics/getProjectList'
  // };

  // $http(req).then(function(response) {
  //   $scope.names = response.data;
  //   $scope.selectedName=$scope.names[0];

  //   for (var i = 0; i < app.scopArray.length; i++) {
  //     app.scopArray[i].init($scope.selectedName,$('#date').val());
  //   }
  // }, function(response) {
  //   console.error("request failed");
  // })
}]);

app.controller('MainController', ['$scope', '$http', function($scope, $http) {

  $scope.names = ["逻辑用户并发曲线图", "独立IP并发数曲线图", "并发流量曲线图"];
  app.scopArray.push($scope);
  $scope.init = function(project, date) {

    var req = {
      method: 'GET',

      url: '/statistics/line',
      params: {
        project: project,
        date: date,
      }
    };

    $http(req).then(function(response) {
      var m = new Map();

      for (var i = 0; i < 24; i++) {
        var hours = i + ":00";
        if (i < 10)
          hours = '0' + hours;
        m.put(hours, [0, 0, 0]);
      }
      //var labels = ["00:00","00:00","00:00","00:00","00:00","00:00","00:00","00:00","00:00","00:00",];
      for (var i = 0; i < response.data.length; i++) {

        var date = new Date(response.data[i].LOG_TIMELEVEL * 1000);
        var hours = date.getHours() + ":00";
        if (date.getHours() < 10)
          hours = '0' + hours;
        m.put(hours, [response.data[i].PERSION, response.data[i].IP, response.data[i].BYTES]);
      }

      function dataStruct() {
        this.labels = [];
        this.datasets = [{
          fillColor: "rgba(220,220,220,0.5)",
          strokeColor: "rgba(220,220,220,1)",
          pointColor: "rgba(220,220,220,1)",
          pointStrokeColor: "#fff",
          label: "测试",
          data: []
        }];
      }

      for (var i = 2; i >= 0; i--) {
        var data = new dataStruct();
        data.labels = m.keys;
        data.datasets[0].data.length = 0;
        data.datasets[0].label = $scope.names[i];
        for (var j = 0; j < 24; j++) {
          var hours = j + ":00";
          if (j < 10)
            hours = '0' + hours;
          data.datasets[0].data[j] = m.get(hours)[i];
        }

        // $('#lineChart').remove(); // this is my <canvas> element
        // $('#lineChartParent').append('<canvas id="lineChart" height="230"></canvas>');

        var id = "page1-item1-chart" + (i + 1);

        $('#' + id).remove(); // this is my <canvas> element
        $('#page1-item' + (i + 1)).append('<canvas id="' + id + '" ></canvas>');

        var ctx = document.getElementById(id).getContext("2d");
        new Chart(ctx, {
          type: 'line',
          data: data
        });
      }
    }, function(response) {
      console.error("request failed");
    })
  }

  app.mainScope.onComplete($scope);

}]);


app.controller('Page2Controller', ['$scope', '$http', function($scope, $http) {

  $scope.names = ["访问方式分布", "访问结果分布", "访问协议分布"];
  app.scopArray.push($scope);
  var colorArray = ["#4BC0C0", "#FFCE56", "#D97041", "#C7604C", "#21323D", "#9D9B7F", "#7D4F6D", "#584A5E", "#845BAF", "#FF6384", "#E7E9ED", "#36A2EB"];

  function dataStruct() {
    this.value = 0;
    this.color = "#D97041";
    this.label = "测试";
  }

  $scope.initChart = function(project, date, url, chartdata, idindex) {

    var req = {
      method: 'GET',
      url: url,
      params: {
        project: project,
        date: date,
      }
    };

    $http(req).then(function(response) {

      var id = null;

      for (var i = 0; i < response.data.length; i++) {
        var sData = new dataStruct();

        chartdata.datasets[0].data.push(
          response.data[i].COUNT
        );
        chartdata.datasets[0].backgroundColor.push(
          colorArray[i]
        );
        chartdata.datasets[0].hoverBackgroundColor.push(
          colorArray[i]
        );
        chartdata.labels.push(
          response.data[i].NAME
        );

      }


      // var id = "page2-item1-chart1";

      // $('#' + id).remove(); // this is my <canvas> element
      // $('#page2-item1').append('<canvas id="' + id + '" ></canvas>');

      var id = "page2-item1-chart" + (idindex + 1);

      $('#' + id).remove(); // this is my <canvas> element
      $('#page2-item' + (idindex + 1)).append('<canvas id="' + id + '" ></canvas>');

      if (null != document.getElementById(id)) {
        var ctx = document.getElementById(id).getContext("2d");
        var myPolarArea = new Chart(ctx, {
          type: 'doughnut',
          data: chartdata
        });
      }

    }, function(response) {
      console.error("request failed");
    })
  }

  $scope.init = function(project, date) {
    var chartdata = {
      labels: [],
      datasets: [{
        data: [],
        backgroundColor: [],
        hoverBackgroundColor: []
      }]

    };
    $scope.initChart(project, date, '/statistics/getReqMethodData', chartdata, 0)

    var chartdata1 = {
      labels: [],
      datasets: [{
        data: [],
        backgroundColor: [],
        hoverBackgroundColor: []
      }]

    };
    $scope.initChart(project, date, '/statistics/getReqResultData', chartdata1, 1)

    var chartdata2 = {
      labels: [],
      datasets: [{
        data: [],
        backgroundColor: [],
        hoverBackgroundColor: []
      }]

    };
    $scope.initChart(project, date, '/statistics/getReqTypeData', chartdata2, 2)
  }
  
  app.mainScope.onComplete($scope);
}]);

app.controller('Page3Controller', ['$scope', '$http', function($scope, $http) {

  $scope.names = ["并发访问TOP10", "并发流量TOP10", "最热页面", "最慢页面"];
  app.scopArray.push($scope);

  $scope.visits = null;
  $scope.bytes = null;
  $scope.hotpage = null;
  $scope.slowpage = null;

  $scope.init = function(project, date) {
    var req = {
      method: 'GET',
      url: '/statistics/getTopVisit',
      params: {
        project: project,
        number: 10
      }
    };

    $http(req).then(function(response) {
      $scope.visits = response.data;
      for (var i = 0; i < $scope.visits.length; i++) {
        $scope.visits[i].TIME = (new Date($scope.visits[i].TIME *1000)).Format("yyyy-MM-dd hh:mm:ss");
      }
    }, function(response) {
      console.error("request failed");
    });

    req.url = '/statistics/getTopBytes';
    $http(req).then(function(response) {
      $scope.bytes = response.data;
      for (var i = 0; i < $scope.bytes.length; i++) {
        $scope.bytes[i].TIME = (new Date($scope.bytes[i].TIME *1000)).Format("yyyy-MM-dd hh:mm:ss");
      }
    }, function(response) {
      console.error("request failed");
    });

    req.url = '/statistics/getTopPage';
    $http(req).then(function(response) {
      $scope.hotpage = response.data;
    }, function(response) {
      console.error("request failed");
    });

    req.url = '/statistics/getTopSlowPage';
    $http(req).then(function(response) {
      $scope.slowpage = response.data;
    }, function(response) {
      console.error("request failed");
    });
  }
  
  app.mainScope.onComplete($scope);
}]);